import { useModel } from "@umijs/max"
import type { TableProps } from "antd"
import { App, Form, Input, InputNumber, Table } from "antd"
import React, { useEffect, useState } from "react"

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean
  dataIndex: string
  title: any
  inputType: "number" | "text"
  record: any
  index: number
}

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  let inputNode
  if (inputType === "number") {
    inputNode = <InputNumber />
  } else if (inputType === "text") {
    inputNode = <Input />
  }

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: dataIndex !== "registerTime" && dataIndex !== "lastLoginTime",
              message: `Please Input ${title}!`
            }
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

const PcDataCount: React.FC = () => {
  const [form] = Form.useForm()
  const [editingKey, setEditingKey] = useState(0)
  // 是否重新加载数据
  const [isReload, setIsReload] = useState(true)
  const { callPy, wsIsOpenRef } = useModel("websocketModel")
  const { serverData } = useModel("eapModel", (ret) => ({
    serverData: ret.eapData.serverPcDataCount
  }))
  const { message } = App.useApp()

  useEffect(() => {
    const fetchData = async () => {
      console.log("PcDataCount 表单初始化")
      try {
        const response = await callPy("eapHdr", "get_pc_data_count_from_web", [])
        if (response.state) {
        } else {
          message.error("表单数据获取失败:" + response.info)
        }
      } catch (error) {
        console.log("数据加载失败", error)
      } finally {
        // 这一步很重要,不然下一次isReload为True的时候收不到变化
        setIsReload(false)
      }
    }

    if (isReload) {
      if (wsIsOpenRef.current) {
        fetchData()
      } else {
        setTimeout(() => {
          fetchData()
        }, 1000)
      }
    }
  }, [isReload])
  const isEditing = (record: any) => record.key === editingKey

  const cancel = () => {
    setEditingKey(0)
  }

  const columns = [
    {
      title: "ID",
      dataIndex: "ID",
      editable: false,
      width: "33%",
      inputType: "true",
      key: "1"
    },
    {
      title: "计数",
      dataIndex: "COUNT",
      editable: false,
      width: "33%",
      inputType: "string",
      key: "2"
    },
    {
      title: "更新时间",
      dataIndex: "UPDATETIME",
      editable: false,
      width: "33%",
      inputType: "string",
      key: "3"
    }
  ]

  const mergedColumns: TableProps<any>["columns"] = columns.map((col) => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        inputType: col.inputType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    }
  })

  return (
    <Form form={form} component={false}>
      <Table<any>
        components={{
          body: { cell: EditableCell }
        }}
        rowKey="ID"
        bordered
        dataSource={serverData}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{ onChange: cancel, pageSize: 8 }}
      />
    </Form>
  )
}

export default () => (
  <App>
    <PcDataCount />
  </App>
)
